package com.xinz.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.xinz.model.BaseModel;

public abstract class BaseDao<T extends BaseModel> {

	private static final Logger log = LoggerFactory.getLogger(BaseDao.class);
	
	protected static final String DB_MASTER = "master";
	protected static final String DB_SLAVE = "slave";
	
	/**
	 * 更新数据操作
	 * @param datastore
	 * @param clazz
	 * @return
	 */
	public UpdateOperations<T> getUpdateOperations(Datastore datastore, Class<T> clazz) {
		return datastore.createUpdateOperations(clazz);
	}
	
	/**
	 * 获取查询对象
	 * @param datastore
	 * @param clazz
	 * @return
	 */
	public Query<T> getQuery(Datastore datastore, Class<T> clazz) {
		return datastore.createQuery(clazz);
	}
	
	/**
	 * 保存
	 * @param datastore
	 * @param model
	 */
	public void save(Datastore datastore, T model) {
		try{
			datastore.save(model);
		}
		catch(Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 写操作肯定是在master
	 * @param model
	 */
	public void save(T model) {
		try {
			Datastore datastore = DBManager.getDatastore();
			datastore.save(model);
		}
		catch(Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 更新
	 * @param datastore
	 * @param query
	 * @param ops
	 */
	public void update(Datastore datastore, Query<T> query, UpdateOperations<T> ops) {
		try {
			datastore.update(query, ops);
		}
		catch(Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 删除
	 * @param datastore
	 * @param query
	 */
	public void delete(Datastore datastore, Query<T> query) {
		try {
			datastore.delete(query);
		}
		catch(Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
